import { Injectable } from '@angular/core';
import {
  HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse
} from '@angular/common/http';

import { Observable } from 'rxjs';
import {tap} from 'rxjs/operators/tap';
import {Router} from '@angular/router';

@Injectable()
export class AuthInterceptor implements HttpInterceptor{

  constructor(private router: Router) { }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    let item = localStorage.getItem('access_token');
    let authReq = req.clone();
    if (item) {
      authReq = req.clone({
        headers: req.headers.set('token',item)
      });
    }
    return next.handle(authReq)
      .pipe(
        tap(
          event => {
            if (event instanceof HttpResponse) {
              if (event.body.code === 'UN_AUTHORIZED') {
                this.router.navigate(['/login']);
              }
            }
            },
          error => {
            console.log('error');
          }
        )
      );
  }
  
}
